<template>
  <div class="app-container">
    <!--    <el-switch-->
    <!--      v-model="showType"-->
    <!--      active-text="管理练习"-->
    <!--      inactive-text="管理实验"/>-->
    <div>
      <el-switch
        v-model="enableLimit"
        active-color="#13ce66"
        active-text="分页查询"
        inactive-text="查询所有并统计"
        inactive-color="#00BFFF"
        @change="fetchEmployeeData"
      />
    </div>
    <br>
    <div>
      <el-table
        v-loading="listLoading"
        :data="employeeList"
        :row-class-name="tableRowClassName"
        :summary-method="getSummaries"
        class="el-table"
        element-loading-text="数据加载中，请稍后"
        border
        show-summary
        sum-text="统计"
        fit
        stripe
        highlight-current-row>

        <el-table-column type="expand" style="width: 100%">

          <template slot-scope="scope">
            <el-form label-position="left" inline class="demo-table-expand" label-width="150px" style="width: 100%">
              <el-form-item label="工号：" style="width: 100%">
                <span>{{ scope.row.employeeId }}</span>
              </el-form-item>
              <br>
              <el-form-item label="姓名：">
                <el-input id="mod_name" v-model="scope.row.name" class="expanded_input"/>
              </el-form-item>
              <br>

              <el-form-item label="年龄：">
                <el-input id="mod_age" v-model="scope.row.age" type="number"/>
              </el-form-item>
              <br>

              <el-form-item label="性别：">
                <template>
                  <el-radio v-model="scope.row.sex " label="男">男</el-radio>
                  <el-radio v-model="scope.row.sex " label="女">女</el-radio>
                </template>
              </el-form-item>
              <br>

              <el-form-item label="部门：">
                <template>
                  <el-select v-model="scope.row.department.departId" placeholder="请选择">
                    <el-option
                      v-for="item in departList"
                      :key="item.departId"
                      :label="item.name"
                      :value="item.departId"/>
                  </el-select>
                </template>
              </el-form-item>
              <br>
              <el-form-item label="工作状态：">
                <template>
                  <el-select v-model="scope.row.state" placeholder="请选择">
                    <el-option
                      v-for="item in workStateOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                </template>
              </el-form-item>
              <br>

              <el-form-item label="手机号：">
                <el-input id="mod_phone" v-model="scope.row.phone"/>
              </el-form-item>
              <br>

              <el-form-item label="邮箱：">
                <el-input id="mod_email" v-model="scope.row.email"/>
              </el-form-item>
              <br>

              <el-form-item label="地址：">
                <el-input id="mod_address" v-model="scope.row.address" type="textarea" class="expanded_input"/>
              </el-form-item>
              <br>

              <el-form-item label="创建时间：">
                <span>{{ scope.row.gmtCreated | formatDate }}</span>
              </el-form-item>
              <br>
              <el-form-item label="最后修改时间：">
                <span>{{ scope.row.gmtModified | formatDate }}</span>
              </el-form-item>
              <br>
              <br>
              <el-form-item>
                <el-row>
                  <el-button type="primary" plain @click="saveModRow(scope.row.employeeId, scope.row)">保存修改</el-button>
                </el-row>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>

        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column
          :sort-method="sortByDepart"
          :filters="departFilter"
          :filter-method="filterDepartHandler"
          prop="depart"
          column-key="name"
          label="部门"
          align="center"
          show-overflow-tooltip
          width="150"
          sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.department.name }}</span>
          </template>
        </el-table-column>

        <el-table-column :sort-method="sortBySex" label="性别" align="center" show-overflow-tooltip width="150" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.sex }}</span>
          </template>
        </el-table-column>
        <el-table-column :sort-method="sortByAge" label="年龄" align="center" show-overflow-tooltip width="150" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.age }}</span>
          </template>
        </el-table-column>
        <el-table-column :sort-method="sortWorkingState" label="工作状态" width="110" align="center" sortable>
          <template slot-scope="scope">
            <el-tag :type="scope.row.state | statusFilter">{{ scope.row.state | statusFilter2 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" show-overflow-tooltip width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" align="center" show-overflow-tooltip width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" align="center" show-overflow-tooltip width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" label="添加时间" width="200" sortable>
          <template slot-scope="scope">
            <i class="el-icon-time"/>
            <span>{{ scope.row.gmtCreated | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" label="上次更新时间" width="200" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.gmtModified | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button size="small" @click.native.prevent="modRow(scope.$index, exeList)">编辑</el-button>
            &nbsp;&nbsp;
            <el-button type="danger" size="small" @click.native.prevent="deleteRow(scope.$index, employeeList)">移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px; text-align: center">
        <el-pagination
          v-if="enableLimit"
          :total="totalSize"
          :current-page.sync="currentPage"
          :page-size="10"
          background
          layout="prev, pager, next"
          @current-change="fetchEmployeeData"/>
      </div>
    </div>
  </div>
</template>

<script>/* eslint-disable indent */

import { deleteEmployee, getEmployees, updateEmployee } from '../../../../api/employee'
import { getAllDepartments } from '../../../../api/department'

export default {
  filters: {
    sexFilter(sex) {
      return sex === '男' ? '1' : '2'
    },
    statusFilter(status) {
      if (status === 'WORKING') {
        return 'success'
      } else if (status === 'RETIRE') {
        return 'warning'
      } else if (status === 'QUIT') {
        return 'info'
      }
    },
    statusFilter2(status) {
      if (status === 'WORKING') {
        return '在职'
      } else if (status === 'RETIRE') {
        return '退休'
      } else if (status === 'QUIT') {
        return '离职'
      }
    },
    formatDate: function(val) {
      const dateFormat = function(date, format) {
        date = new Date(date)
        const o = {
          'M+': date.getMonth() + 1,
          'd+': date.getDate(),
          'H+': date.getHours() + 8,
          'm+': date.getMinutes(),
          's+': date.getSeconds(),
          'q+': Math.floor((date.getMonth() + 3) / 3),
          'S': date.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
          format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        }
        for (const k in o) {
          if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
          }
        }
        return format
      }
      return dateFormat(val, 'yyyy-MM-dd HH:mm:ss')
    }
  },
  data() {
    return {
      showType: true,
      employeeList: null,
      listLoading: true,
      departList: [],
      departFilter: [],
      modExeForm: {
        numPerGrp: -1,
        sort: -1
      },
      enableLimit: true,
      workStateOptions: [{
        value: 'WORKING',
        label: '在职'
      }, {
        value: 'RETIRE',
        label: '退休'
      }, {
        value: 'QUIT',
        label: '离职'
      }],
      totalSize: 0,
      currentPage: 1
    }
  },
  created() {
    this.fetchEmployeeData()
    this.fetchDepartmentData()
  },
  methods: {

    filterDepartHandler(value, row, column) {
      console.log(value + '=' + row + ' ' + column)
      // const property = column['property']
      return row.department.departId === value
    },
    sortWorkingState(a, b) {
      return a.state.localeCompare(b.state)
    },
    sortBySort(a, b) {
      return a.sort - b.sort
    },
    sortByDepart(a, b) {
      return a.department.name.localeCompare(b.department.name)
    },
    sortBySex(a, b) {
      return a.sex.localeCompare(b.sex)
    },
    sortByAge(a, b) {
      return a.age - b.age
    },
    modRow() {
      this.$message({
        message: '点击左侧箭头展开详细信息进行编辑',
        type: 'info'
      })
    },
    saveModRow(id, rowObj) {
      this.listLoading = true
      const that = this
      this.$nextTick(() => {
        updateEmployee(rowObj).then(response => {
          console.log(response)
          that.displayResult(response, '修改')
          if (response.success) {
            that.fetchEmployeeData()
          }
          that.listLoading = false
        })
      })
    },
    deleteRow(index, rows) {
      const that = this
      console.log(rows[index])
      deleteEmployee(rows[index].employeeId).then(response => {
        console.log(response)
        that.displayResult(response, '删除')
        if (response.success) {
          rows.splice(index, 1)
        }
      })
    },
    tableRowClassName({ row, rowIndex }) {
      // if (rowIndex % 4 === 0) {
      //   return 'warning-row'
      // } else if (rowIndex % 4 === 2) {
      //   return 'success-row'
      // }
      return ''
    },

    fetchEmployeeData() {
      this.listLoading = true
      const that = this
      getEmployees(this.currentPage, 10, this.enableLimit).then(response => {
        const result = response.data
        console.log(result)
        that.employeeList = result.data
        that.totalSize = result.totalSize
        that.listLoading = false
      })
    },

    fetchDepartmentData() {
      getAllDepartments().then(response => {
        this.departList = response.data

        const keySet = new Set()
        const newArr = []
        this.departList.forEach((department) => {
          if (!keySet.has(department.departId)) {
            keySet.add(department.departId)
            newArr.push({
              'text': department.name,
              'value': department.departId
            })
          }
        })
        this.departFilter = newArr
      })
    },
    displayResult(response, text) {
      if (!response.success) {
        this.$message({
          message: text + '出错！' + response.message,
          type: 'error'
        })
        return
      }
      this.$message({
        message: text + '成功!',
        type: 'success'
      })
    },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '统计'
            return
          }
          if (index === 1) {
            return
          }
          if (data.length === 0) {
            return
          }

          if (index === 2) {
            sums[2] = data.length + '人'
            return
          }

          if (index === 3) {
            const keySet = new Set()
            data.forEach((employee) => {
              keySet.add(employee.department.departId)
            })
            sums[index] = keySet.size + '个部门'
            return
          }

          if (index === 4) {
            const sexA = data.filter((employee) => employee.sex === '男').length
            const sexB = data.filter((employee) => employee.sex === '女').length
            sums[index] = '男: ' + sexA + ' , 女: ' + sexB
            return
          }

          if (index === 5) {
            let min = 999
            let max = 1
            let total = 0
            data.forEach((employee) => {
                if (employee.age > max) {
                  max = employee.age
                }
                if (employee.age < min) {
                  min = employee.age
                }
                total += employee.age
              }
            )
            sums[index] = '最小: ' + min + ' , 最大: ' + max + ' , 平均: ' + (total / data.length).toFixed(2)
            return
          }

          if (index === 6) {
            let workCount = 0
            let quitCount = 0
            let retireCount = 0
            data.forEach((employee) => {
              if (employee.state === 'QUIT') {
                quitCount++
              } else if (employee.state === 'RETIRE') {
                retireCount++
              } else if (employee.state === 'WORKING') {
                workCount++
              }
            })
            sums[index] = '在职: ' + workCount + '人 , 离职: ' + quitCount + '人 , 退休: ' + retireCount + '人'
            return
          }
          sums[index] = '无数据项统计'
        }
      )

      return sums
    }
  }
}
</script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .expanded_input {
    width: 555px;
  }
</style>
